<template>
  <view class="container">
    <!-- 返回导航栏 -->
    <view class="nav-bar">
      <text class="back-icon" @click="goBack">返回</text>
      <text class="title">药品列表</text>
    </view>
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper" :class="{ 'expanded': isSearchActive }">
        <text class="iconfont icon-search" @click="toggleSearch"></text>
        <input
          v-model="searchKeyword"
          class="search-input"
          :class="{ 'active': isSearchActive }"
          placeholder="搜索药品名称"
          @confirm="handleSearch"
          @blur="handleSearchBlur"
        />
      </view>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-section">
      <scroll-view scroll-x class="category-scroll">
        <view class="category-list">
          <view
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            :class="{ 'active': selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            {{ category.name }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 药品列表 -->
    <scroll-view
      scroll-y
      class="medicine-list"
      @scrolltolower="loadMore"
    >
      <view class="list-grid">
        <view
          v-for="medicine in medicineList"
          :key="medicine.id"
          class="medicine-card"
          @click="navigateToDetail(medicine.id)"
        >
          <view class="medicine-status">
            <view class="status-tag" :class="medicine.status">
              {{ getStatusText(medicine.status) }}
            </view>
            <view class="expiry-warning" v-if="medicine.status === 'nearExpiry'">
              <text class="iconfont icon-warning"></text>
              <text class="warning-text">即将过期</text>
            </view>
          </view>
          <image
            :src="medicine.imageUrl || medicine.defaultImageUrl || '/static/medicine-placeholder.png'"
            mode="aspectFill"
            class="medicine-image"
          />
          <view class="medicine-info">
            <text class="medicine-name">{{ medicine.name }}</text>
            <text class="medicine-desc">{{ medicine.efficacy }}</text>
            <text class="medicine-spec" v-if="medicine.specification">规格：{{ medicine.specification }}</text>
            <text class="medicine-quantity" v-if="medicine.remainingQuantity !== undefined">剩余：{{ medicine.remainingQuantity }}{{ medicine.specification?.includes('片') ? '片' : '盒' }}</text>
            <text class="expiry-date">有效期至：{{ formatDate(medicine.expiryDate) }}</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import type { Medicine, MedicineCategory } from '@/types'
import { getMedicineList, getCategoryList } from '@/api/medicine'

// 格式化日期
const formatDate = (date: string | Date | undefined) => {
  if (!date) return '未知'
  const d = new Date(date)
  if (isNaN(d.getTime())) return '无效日期'
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 搜索相关
const isSearchActive = ref(false)
const searchKeyword = ref('')

// 跳转到药品详情页
const navigateToDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/medicine/detail?id=${id}`
  })
}

// 分类数据
const categories = ref<MedicineCategory[]>([])

// 药品列表数据
const medicineList = ref<Medicine[]>([])
const loading = ref(false)
const page = ref(1)
const limit = ref(10)
const hasMore = ref(true)
const selectedCategory = ref(0)

// 切换搜索栏
const toggleSearch = () => {
  isSearchActive.value = !isSearchActive.value
  if (isSearchActive.value) {
    // 展开搜索栏后自动聚焦输入框
    nextTick(() => {
      const input = document.querySelector('.search-input') as HTMLInputElement
      input?.focus()
    })
  } else {
    searchKeyword.value = ''
    handleSearch()
  }
}

// 处理搜索框失焦
const handleSearchBlur = () => {
  if (searchKeyword.value.trim() === '') {
    isSearchActive.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  isSearchActive.value = false
  page.value = 1
  hasMore.value = true
  loadMedicineList()
}

// 选择分类
const selectCategory = (categoryId: number) => {
  selectedCategory.value = categoryId
  page.value = 1
  hasMore.value = true
  loadMedicineList()
}

// 状态文本映射
const getStatusText = (status: string) => {
  const statusMap = {
    normal: '正常',
    expired: '已过期',
    nearExpiry: '即将过期'
  }
  return statusMap[status] || '未知'
}

// 更新药品状态
const updateMedicineStatus = (medicine: Medicine) => {
  const now = new Date()
  const expiryDate = new Date(medicine.expiryDate)
  const thirtyDaysFromNow = new Date(now.getTime() + (30 * 24 * 60 * 60 * 1000))

  if (expiryDate < now) {
    medicine.status = 'expired'
  } else if (expiryDate <= thirtyDaysFromNow) {
    medicine.status = 'nearExpiry'
  } else {
    medicine.status = 'normal'
  }
}

// 加载药品列表
const loadMedicineList = async () => {
  if (loading.value || !hasMore.value) return
  loading.value = true
  
  try {
    const { data } = await getMedicineList({
      categoryId: selectedCategory.value ? String(selectedCategory.value) : undefined,
      keyword: searchKeyword.value,
      page: page.value,
      limit: limit.value
    })
    
    // 更新每个药品的状态
    data.medicines.forEach(medicine => {
      updateMedicineStatus(medicine)
    })
    
    if (page.value === 1) {
      medicineList.value = data.medicines
    } else {
      medicineList.value.push(...data.medicines)
    }
    
    hasMore.value = data.medicines.length === limit.value
    if (hasMore.value) {
      page.value++
    }
  } catch (error) {
    console.error('获取药品列表失败:', error)
    uni.showToast({
      title: '获取药品列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const { data } = await getCategoryList()
    categories.value = [{ id: 0, name: '全部' }, ...data.map(item => ({
      id: item._id,
      name: item.name
    }))]
  } catch (error) {
    console.error('获取分类列表失败:', error)
    uni.showToast({
      title: '获取分类列表失败',
      icon: 'none'
    })
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadCategories()
  loadMedicineList()
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-top: var(--status-bar-height);
  padding-bottom: var(--window-bottom);
  padding-top: 240rpx;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  z-index: 100;
  border-bottom: 1rpx solid #f0f0f0;

  .back-icon {
    font-size: 28rpx;
    color: #333333;
  }

  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-right: 44rpx;
  }
}

.search-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: #ffffff;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  z-index: 100;
  
  .search-input-wrapper {
    position: absolute;
    right: 30rpx;
    width: 88rpx;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    display: flex;
    align-items: center;
    padding: 0 24rpx;
    transition: all 0.3s ease-out;
    overflow: hidden;
    
    &.expanded {
      left: 30rpx;
      width: auto;
    }
  }
  
  .icon-search {
    font-size: 40rpx;
    color: #999999;
    flex-shrink: 0;
  }
  
  .search-input {
    flex: 1;
    height: 72rpx;
    margin-left: 16rpx;
    font-size: 28rpx;
    opacity: 0;
    transition: opacity 0.3s ease-out;
    
    &.active {
      opacity: 1;
    }
  }
}

.filter-section {
  position: fixed;
  top: 88rpx;
  left: 0;
  right: 0;
  background: #ffffff;
  z-index: 99;
  
  .category-scroll {
    white-space: nowrap;
    padding: 20rpx 30rpx;
  }
  
  .category-list {
    display: inline-flex;
    gap: 20rpx;
  }
  
  .category-item {
    padding: 12rpx 24rpx;
    border-radius: 32rpx;
    font-size: 28rpx;
    color: #666666;
    background: #f5f5f5;
    
    &.active {
      color: #ffffff;
      background: #018d71;
    }
  }
}

.medicine-list {
  height: calc(100vh - 180rpx);
  
  .list-grid {
    padding: 30rpx;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 30rpx;
  }
}

.medicine-card {
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  position: relative;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  
  .status-dot {
    position: absolute;
    top: 16rpx;
    right: 16rpx;
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    z-index: 1;
    
    &.normal {
      background: #52c41a;
    }
    
    &.expired {
      background: #f5222d;
    }
    
    &.nearExpiry {
      background: #faad14;
    }
  }
  
  .medicine-image {
    width: 100%;
    height: 240rpx;
    background: #f5f5f5;
  }
  
  .medicine-info {
    padding: 20rpx;
    
    .medicine-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 12rpx;
      line-height: 1.3;
    }
    
    .medicine-desc {
      font-size: 26rpx;
      color: #666666;
      margin-bottom: 12rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      line-height: 1.4;
    }
    
    .medicine-spec,
    .medicine-quantity {
      font-size: 26rpx;
      color: #666666;
      margin-bottom: 8rpx;
      line-height: 1.4;
    }
    
    .expiry-date {
      font-size: 26rpx;
      color: #999999;
      line-height: 1.4;
    }
  }
}

.medicine-status {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10rpx;

  .status-tag {
    padding: 4rpx 16rpx;
    border-radius: 24rpx;
    font-size: 24rpx;
    color: #ffffff;

    &.normal {
      background: #52c41a;
    }

    &.expired {
      background: #f5222d;
    }

    &.nearExpiry {
      background: #faad14;
    }
  }

  .expiry-warning {
    display: flex;
    align-items: center;
    gap: 4rpx;
    padding: 4rpx 12rpx;
    background: rgba(250, 173, 20, 0.1);
    border-radius: 16rpx;

    .icon-warning {
      font-size: 24rpx;
      color: #faad14;
    }

    .warning-text {
      font-size: 22rpx;
      color: #faad14;
    }
  }
}

.loading {
  text-align: center;
  padding: 30rpx;
  color: #999999;
  font-size: 28rpx;
}
</style>